<template>
  <s-layout title="用户信息" class="set-userinfo-wrap">
    <uni-forms
      :model="state.model"
      :rules="state.rules"
      labelPosition="left"
      border
      class="form-box"
    >


      <view class="bg-white ss-p-x-30">
        <uni-forms-item name="avatar" label="头像">
          <view class="avatar-container" @tap="onChangeAvatar">
            <image 
              class="avatar-img" 
              :src="getAvatarUrl()" 
              mode="aspectFill"
              @error="onAvatarError" 
              @load="onAvatarLoad"
            />
            <view class="avatar-overlay">
              <text class="avatar-text">点击更换</text>
            </view>
          </view>
        </uni-forms-item>

        <uni-forms-item name="nickname" label="昵称">
          <uni-easyinput
            v-model="state.model.nickname"
            type="nickname"
            placeholder="设置昵称"
            :inputBorder="false"
            :placeholderStyle="placeholderStyle"
          />
        </uni-forms-item>

        <uni-forms-item name="gender" label="性别">
          <view class="ss-flex ss-col-center ss-h-100">
            <radio-group @change="onChangeGender" class="ss-flex ss-col-center">
              <label class="radio" v-for="item in genderRadioMap" :key="item.value">
                <view class="ss-flex ss-col-center ss-m-r-32">
                  <radio
                    :value="item.value"
                    color="var(--ui-BG-Main)"
                    style="transform: scale(0.8)"
                    :checked="item.value == state.model.gender"
                  />
                  <view class="gender-name">{{ item.name }}</view>
                </view>
              </label>
            </radio-group>
          </view>
        </uni-forms-item>

        <uni-forms-item name="mobile" label="手机号" @tap="onChangeMobile">
          <uni-easyinput
            v-model="state.model.phone"
            placeholder="请绑定手机号"
            :inputBorder="false"
            disabled
            :styles="{ disableColor: '#fff' }"
            :placeholderStyle="placeholderStyle"
            :clearable="false"
          >
            <template v-slot:right>
              <view class="ss-flex ss-col-center">
                <su-radio v-if="userInfo.verification?.mobile" :modelValue="true" />
                <button v-else class="ss-reset-button ss-flex ss-col-center ss-row-center">
                  <text class="_icon-forward" style="color: #bbbbbb; font-size: 26rpx"></text>
                </button>
              </view>
            </template>
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item name="birthday" label="生日">
          <uni-datetime-picker 
            v-model="state.model.birthday"
            type="date"
            :clear-icon="false"
            placeholder="选择生日"
            :border="false"
            :inputBorder="false"
            :placeholderStyle="placeholderStyle"
          />
        </uni-forms-item>



        <uni-forms-item name="remark" label="个人简介">
          <uni-easyinput
            v-model="state.model.remark"
            type="textarea"
            placeholder="请输入个人简介"
            :inputBorder="false"
            :placeholderStyle="placeholderStyle"
            :autoHeight="true"
            :maxlength="200"
          />
        </uni-forms-item>


      </view>

      <view class="bg-white ss-m-t-14">
        <uni-list>
          <uni-list-item
            clickable
            @tap="sheep.$router.go('/pages/user/address/list')"
            title="地址管理"
            showArrow
            :border="false"
            class="list-border"
          ></uni-list-item>

        </uni-list>
      </view>
    </uni-forms>



    <su-fixed bottom placeholder bg="none">
      <view class="footer-box ss-p-20">
        <button class="ss-rest-button logout-btn ui-Shadow-Main" @tap="onSubmit">保存</button>
      </view>
    </su-fixed>
  </s-layout>
</template>

<script setup>
  import { computed, ref, reactive, onBeforeMount, unref } from 'vue';
  import { mobile, password, username } from '@/sheep/validate/form';
  import sheep from '@/sheep';
  import { clone } from 'lodash';
  import { showAuthModal } from '@/sheep/hooks/useModal';

  const state = reactive({
    model: {},
    rules: {},
    thirdOauthInfo: null,
  });

  const placeholderStyle = 'color:#BBBBBB;font-size:28rpx;line-height:normal';

  const genderRadioMap = [
    {
      name: '男',
      value: '1',
    },
    {
      name: '女',
      value: '2',
    },
    {
      name: '未知',
      value: '0',
    },
  ];

  const userInfo = computed(() => sheep.$store('user').userInfo);

  function onChangeGender(e) {
    state.model.gender = e.detail.value;
  }
  const onChangeUsername = () => {
    !state.model.verification?.username && showAuthModal('changeUsername');
  };

  const onChangeMobile = () => {
    showAuthModal('changeMobile');
  };

  function onChooseAvatar(e) {
    const tempUrl = e.detail.avatarUrl || '';
    uploadAvatar(tempUrl);
  }

  function onChangeAvatar() {
    uni.chooseImage({
      success: async (chooseImageRes) => {
        const tempUrl = chooseImageRes.tempFilePaths[0];
        uploadAvatar(tempUrl);
      },
    });
  }

  async function uploadAvatar(tempUrl) {
    if (!tempUrl) return;
    try {
      uni.showLoading({
        title: '上传中...',
        mask: true
      });
      
      const result = await sheep.$api.app.upload(tempUrl, 'ugc');
      
      if (result) {
        const avatarUrl = JSON.parse(result).data;
        state.model.avatar = avatarUrl;
        
        setTimeout(() => {
          const timestamp = new Date().getTime();
          state.model.avatar = avatarUrl + '?t=' + timestamp;
        }, 100);
        
        sheep.$helper.toast('头像上传成功');
      } else {
        throw new Error('上传失败');
      }
    } catch (error) {
      sheep.$helper.toast('头像上传失败，请重试');
    } finally {
      uni.hideLoading();
    }
  }

  function getAvatarUrl() {
    
    if (state.model.avatar) {
      let avatarUrl = state.model.avatar;
      
      if (typeof avatarUrl === 'object' && avatarUrl.data) {
        avatarUrl = avatarUrl.data;
        state.model.avatar = avatarUrl;
      }
      
      if (typeof avatarUrl === 'string') {
        if (avatarUrl.startsWith('http')) {
          return avatarUrl;
        }
        const cdnUrl = sheep.$url.cdn(avatarUrl);
        return cdnUrl;
      }
    }
    
    const defaultUrl = 'https://git-open.oss-cn-shenzhen.aliyuncs.com/ruoyi-mall/uniapp/icons/default_avatar.png';
    return defaultUrl;
  }

  function onAvatarError(e) {
    e.target.src = 'https://git-open.oss-cn-shenzhen.aliyuncs.com/ruoyi-mall/uniapp/icons/default_avatar.png';
  }

  function onAvatarLoad(e) {
    // 头像加载完成
  }

  function onSetPassword() {
    if (state.model.verification.password) {
      showAuthModal('changePassword');
    } else {
      showAuthModal('resetPassword');
    }
  }

  async function bindThirdOauth() {
    let result = await sheep.$platform.useProvider('wechat').bind();
    if (result) {
      getUserInfo();
    }
  }

  function unBindThirdOauth() {
    uni.showModal({
      title: '解绑提醒',
      content: '解绑后您将无法通过微信登录此账号',
      cancelText: '再想想',
      confirmText: '确定',
      success: async function (res) {
        if (res.confirm) {
          const result = await sheep.$platform.useProvider('wechat').unbind();
          if (result) {
            getUserInfo();
          }
        }
      },
    });
  }

  async function onSubmit() {
    try {
      const updateData = {
        avatar: state.model.avatar,
        nickname: state.model.nickname,
        gender: state.model.gender,
        birthday: state.model.birthday,
        remark: state.model.remark,
      };
      
      const result = await sheep.$api.user.update(updateData);
      if (result) {
        sheep.$helper.toast('保存成功');
        getUserInfo();
      } else {
        sheep.$helper.toast('保存失败，请重试');
      }
    } catch (error) {
      sheep.$helper.toast('保存失败，请重试');
    }
  }

  const getUserInfo = async () => {
    try {
      const memberInfo = await sheep.$api.user.profile();
      if (memberInfo) {
        state.model = clone(memberInfo);
        if (state.model.birthday) {
          state.model.birthday = state.model.birthday.split(' ')[0];
        }
      } else {
        const userInfo = await sheep.$store('user').getInfo();
        state.model = clone(userInfo);
      }
    } catch (error) {
      sheep.$helper.toast('获取用户信息失败');
    }
  };

  onBeforeMount(async () => {
    getUserInfo();
  });
</script>

<style lang="scss" scoped>
  :deep() {
    .uni-file-picker {
      border-radius: 50%;
    }

    .uni-file-picker__container {
      margin: -14rpx -12rpx;
    }

    .file-picker__progress {
      height: 0 !important;
    }

    .uni-list-item__content-title {
      font-size: 28rpx !important;
      color: #333333 !important;
      line-height: normal !important;
    }

    .uni-icons {
      font-size: 40rpx !important;
    }

    .is-disabled {
      color: #333333;
    }
  }

  :deep(.disabled) {
    opacity: 1;
  }

  .gender-name {
    font-size: 28rpx;
    font-weight: 500;
    line-height: normal;
    color: #333333;
  }

  .title-box {
    font-size: 28rpx;
    font-weight: 500;
    color: #666666;
    line-height: 100rpx;
  }

  .logout-btn {
    width: 710rpx;
    height: 80rpx;
    background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
    border-radius: 40rpx;
    font-size: 30rpx;
    font-weight: 500;
    color: $white;
  }

  .radio-dark {
    filter: grayscale(100%);
    filter: gray;
    opacity: 0.4;
  }

  .content-img {
    border-radius: 50%;
  }
  .header-box-content {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    overflow: hidden;
    border-radius: 50%;
  }
  .avatar-action {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 0;
    z-index: 1;
    width: 160rpx;
    height: 46rpx;
    background: rgba(#000000, 0.3);

    .avatar-action-btn {
      width: 160rpx;
      height: 46rpx;
      font-weight: 500;
      font-size: 24rpx;
      color: #ffffff;
    }
  }

  .account-list {
    background-color: $white;
    height: 100rpx;
    padding: 0 20rpx;

    .list-img {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .list-name {
      font-size: 28rpx;
      color: #333333;
    }

    .info {
      .avatar {
        width: 38rpx;
        height: 38rpx;
        border-radius: 50%;
        overflow: hidden;
      }

      .name {
        font-size: 28rpx;
        font-weight: 400;
        color: $dark-9;
      }
    }

    .bind-box {
      width: 100rpx;
      height: 50rpx;
      line-height: normal;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 24rpx;

      .bind-btn {
        width: 100%;
        height: 100%;
        border-radius: 25rpx;
        background: #f4f4f4;
        color: #999999;
      }
      .relieve-btn {
        width: 100%;
        height: 100%;
        border-radius: 25rpx;
        background: var(--ui-BG-Main-opacity-1);
        color: var(--ui-BG-Main);
      }
    }
  }

  .list-border {
    font-size: 28rpx;
    font-weight: 400;
    color: #333333;
    border-bottom: 2rpx solid #eeeeee;
  }

  image {
    width: 100%;
    height: 100%;
  }

  .avatar-container {
    position: relative;
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    overflow: hidden;
    border: 2rpx solid #e0e0e0;
    cursor: pointer;

    .avatar-img {
      width: 100%;
      height: 100%;
      border-radius: 60rpx;
    }

    .avatar-overlay {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      text-align: center;
      padding: 8rpx 0;
      font-size: 20rpx;
      transform: translateY(100%);
      transition: transform 0.3s ease;

      .avatar-text {
        font-size: 20rpx;
        color: white;
      }
    }

    &:hover .avatar-overlay {
      transform: translateY(0);
    }
  }
</style>
